package tech.dongliang.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import tech.dongliang.common.model.Tree;
import tech.dongliang.system.dao.SysDeptDao;
import tech.dongliang.system.model.SysDept;
import tech.dongliang.system.service.ISysDeptService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xdzhang
 * @since 2019-01-18
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptDao, SysDept> implements ISysDeptService {

    @Override
    public List<SysDept> list(QueryWrapper<SysDept> queryWrapper) throws Exception {
        queryWrapper.ne("delFlag", -1);
        queryWrapper.orderByAsc("pid", "orderNum");
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public Tree<SysDept> getTree() throws Exception {
        List<Tree<SysDept>> trees = new ArrayList<>();
        List<SysDept> sysDepts = baseMapper.selectList(null);
        for (SysDept sysDept : sysDepts) {
            Tree<SysDept> tree = new Tree<>();
            tree.setId(sysDept.getId().toString());
            tree.setParentId(sysDept.getPid().toString());
            tree.setText(sysDept.getName());
            Map<String, Object> state = new HashMap<>(16);
            state.put("opened", true);
            tree.setState(state);
            trees.add(tree);
        }
        // 默认顶级菜单为０，根据数据库实际情况调整
        Tree<SysDept> t = Tree.build(trees);
        return t;
    }

    @Override
    public int remove(Integer deptId) throws Exception {
        return baseMapper.remove(deptId);
    }

    @Override
    public int childCount(Integer deptId) throws Exception {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("pid", deptId);
        return baseMapper.selectCount(wrapper);
    }

    @Override
    public int getDeptUserNumber(Integer deptId) throws Exception {
        return baseMapper.getDeptUserNumber(deptId);
    }
}
